package com.async_export_demo.export;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.async_export_demo.model.Order;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;

@Component
@Log
public class SyncExportService {
    @Autowired
    private Map<ExportEnum, DataProvider> dataProviderMap;

    private WriteSheet getWriteSheet(long processedDataCount, LinkedList<WriteSheet> writeSheets, long currentProcessCount) {
        if (processedDataCount == 0) {
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "模板").build();
            writeSheets.add(writeSheet);
        } else {
            long count = processedDataCount + currentProcessCount - 200000L * (writeSheets.size() - 1);
            if (count > 200000) {
                writeSheets.add(EasyExcel.writerSheet(writeSheets.size(), "模板" + writeSheets.size()).build());
            }
        }
        return writeSheets.getLast();
    }

    public void syncExportOrder(OutputStream outputStream) {
        long processedDataCount = 0;
        LinkedList<WriteSheet> writeSheets = new LinkedList<>();
        DataProvider<Order> dataProvider = dataProviderMap.get(ExportEnum.ORDER);
        long currentPage = 1;
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream, Order.class).build()) {
            AsyncExportService.ExportContext context = new AsyncExportService.ExportContext();
            Page<Order> page = null;
            // 新建上下文对象,如需传递参数可以放在里面
            do {
                page = dataProvider.getPageData(currentPage++, 1000, context);
                if (!Objects.isNull(page) && Objects.nonNull(page.getRecords()) && !page.getRecords().isEmpty()) {
                    WriteSheet writeSheet = getWriteSheet(processedDataCount, writeSheets, page.getRecords().size());
                    excelWriter.write(page.getRecords(), writeSheet);
                }
            } while (page.hasNext() && page.getCurrent() < 1000);
        }

    }
}
